#!/usr/bin/python3

##-image combining by liuqimin
import os
from PIL import Image
import copy
import re

#-----------------------
def combine(img_list):
    widths = []
    heights = []
    for img in img_list:
        image1 = Image.open(img)
        widths.append(image1.size[0])
        heights.append(image1.size[1])

    w = max(widths)
    h = sum(heights)

    new_im = Image.new(mode='L', size=(w, h), color=255)

    for i in range(0, len(img_list)):
        image1 = Image.open(img_list[i])
        if i == 0:
            new_im.paste(image1, (0, 0))
        else:
            new_im.paste(image1, (0, sum(heights[0:i])))

    return new_im
#-----------combine images files contain underline ('_')----------------------------
def ProcessUnderline(path):

    file_list = set(os.listdir(path))
    flist = copy.deepcopy(file_list)
    ##---first, processing files with '_'-------------
    xx = 0
    for f in file_list:
        x = f.find('_')
        if x == -1:
            continue
        print('f=', f)
        xx = xx + 1

        if not f in flist:  ####has been removed already
            continue
        y = f.rfind('.')
        lst = []
        tt = f[:x] + f[y:]
        print('tt=', tt)
        if tt in file_list:
            lst.append(tt)
            flist.remove(tt)
        for i in range(1, 100):
            tt = f[:x + 1] + str(i) + f[y:]
            if tt in flist:
                lst.append(os.path.join(path, tt))
                flist.remove(tt)
            else:
                break
        if lst != []:
            img = combine(lst)
            img.save(os.path.join(path, f[:x] + f[y:]))
    # ------------------------------


##------------------main-----------------------
path='D:\\临时图书\\物理学-第五版-马文蔚'
out_path='d:\\临时图书\\out'
ProcessUnderline(path)
#----copy files to output path
for f in os.listdir(path):
    if '_' in f:
        continue
    xx=os.path.join(path, f)
    tt=os.path.join(out_path, f)

    os.system('copy '+ xx+ ' '+tt)



file_list = set(os.listdir(path))
flist = copy.deepcopy(file_list)
for f in file_list:
    if '_' in f: ###has been processed by ProcessUnderline
        continue
    if not  f in  flist:
        continue

    xx=re.split('[.-]', f[1:])
    lst=[]              ##clear the list before process

    if len(xx)==4:  ###该题 不包含 小题
        if 'a'+f[1:] in flist: ####确保不是小题的题干
            lst.append( os.path.join( path, 'q'+f[1:]) )
            lst.append( os.path.join( path,'a' + f[1:]) )
            if  not  'q'+f[1:] in flist :
                print ( '数据有缺失！！')
                print('f=', f)
                continue
            img = combine(lst)
            img.save(os.path.join(out_path, f[1:]) )
            flist.remove('a'+f[1:])
            flist.remove('q' + f[1:])

        continue
    elif len(xx)==5:
        tt = xx[0] + '.' + xx[1] + '-' + xx[2]
        if 'q' + tt + '.' + xx[4] in flist:
            lst.append( os.path.join( path,'q' + tt + '.' + xx[4]) )
        lst_tmp=[]
        for i in range(1, 500):
            zz = xx[0] + '.' + xx[1] + '-' + xx[2] + '.' + str(i) + '.' + xx[4]
            if 'q' + zz in flist:
                lst_tmp.append('q' + zz)
                lst.append( os.path.join(path, 'q' + zz) )
                flist.remove('q' + zz)
            else:
                break

        for item in lst_tmp:
            ##--------error detection and warn---------
            if not  'a'+item[1:] in flist:
                print('corresponding answer not found')
                print('question file is ', item)
                continue
            lst.append( os.path.join( path, 'a'+item[1:]) )
            flist.remove('a'+item[1:])
        img = combine(lst)
        img.save(os.path.join(out_path, tt+'.' + xx[4]))



